<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               ref="crud"
               v-model="form"
               :show-column.sync="showColumn"
               :permission="permissionList"
               :page.sync="page"
               :before-open="beforeOpen"
               @sortable-change="sortableChange"
               @row-del="rowDel"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @refresh-change="refreshChange"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @filter-change="filterChange"
               @sort-change="sortChange"
               @row-dblclick="handleRowDBLClick"               
               @on-load="onLoad">
      <template slot-scope="scope" slot="apprProjectFileAddressForm">
        <file-selector
              :fileList="currentRow.apprProjectFileAddress"
              :openType="openType"
              :multiple="true"
              @changeFileList='changeFileList'
            >
        </file-selector>
      </template>
      <template slot-scope="scope" slot="menuForm">
        <div  style="text-align:right; float:right">
          <el-button type="text"  icon="el-icon-time" style="font-weight:normal;" size="large" @click.stop="getHistoryRecord">修改历史</el-button>
        </div> 
      </template>
      <template slot-scope="scope" slot="menu">
        <el-button type="text"
                   size="small"
                   icon="el-icon-s-operation"
                   v-if="permission.tenant_edit"
                   @click.stop="handleSetPrivilege(scope.row)">设置权限
        </el-button>
      </template>
      <template slot-scope="scope" slot="menuLeft">
        <el-button type="primary"
                   size="small"
                   icon="el-icon-user"
                   v-if="permission.general_project_i_batch_add"
                   @click.stop="addProjectAdminUser">初始化管理员
        </el-button>
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   v-if="permission.general_project_i_batch_delete"
                   @click.stop="handleDelete">删 除
        </el-button>
      </template>
      <template slot="menuRight">
        <el-button v-if="permission.general_project_i_download" type="default" @click.stop="exportExcel"  title="下载" icon="el-icon-download" circle size="small"></el-button>
      </template>
    </avue-crud>
    <!-- 
      批量添加数据对话框
     -->
    <el-dialog title="批量导入" width='80%' :close-on-click-modal='false' :visible.sync="batchAddDialog">
      <el-tag>
        项目编号，
        项目名称，
        项目分类，
        项目简称，
        需求编号，
        需求名称，
        主办部门，
        主办科室，
        协办部门，
        建设方式，
        实施方式，
        项目经理，
        项目级别，
      </el-tag>
      <el-tag>
        优先等级，
        预计工作量，
        预算类目，
        预算金额，
        项目状态，
        计划开始日期，
        计划完成日期，
        实际开始日期，
        实际完成日期，
        立项文档地址，
        项目描述，
        备注，
      </el-tag>
      <el-input
        type="textarea"
        :autosize="{ minRows: 10, maxRows: 20}"
        placeholder="请直接从excel粘贴内容"
        v-model="importDataArea">
      </el-input>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" id="copyBtn" @click="handleImport($event)" data-clipboard-target="#pathText">开始导入</el-button>
        <el-button size="small" @click="batchAddDialog = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 
      设置项目权限
     -->
    <el-dialog :title="dialogTitle" width='40%' :close-on-click-modal='false' :visible.sync="setPrivilegeDialog">
      <div v-if="fullscreenLoading" style="width:100%; text-align:center;font-size:30px;top:150px;position:absolute;z-index:5000">
        <i  class="el-icon-loading"></i>
      </div>
      <el-tabs v-model="activeTabName" type="border-card">
        <el-tab-pane label="菜单权限" name="menuPrivilege">
          <el-tree  
            style="height:300px;overflow:auto;"
            :data="menuTreeData"
            show-checkbox
            :expand-on-click-node='false'
            check-on-click-node = 'true'
            check-strictly="true"
            node-key="id"
            ref="menuTree"
            highlight-current
            :default-checked-keys="treeValue"
            @check="getCheckedNodes"
            :props="menuTreeProps">
          </el-tree>
        </el-tab-pane>
      </el-tabs> 
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" id="copyBtn" @click="handleSavePrivilege($event)" icon="el-icon-check">保 存</el-button>
        <el-button size="small" @click="setPrivilegeDialog = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 历史记录 -->
    <update-history ref="historyRecord"></update-history>
  </basic-container>
</template>

<script>
import {createProjectAdminUser} from '@/api/system/sysUserInfoApi';

import {querySysMenuTree,synchronizeSysMenu} from '@/api/system/sysMenuApi';
import {saveOrUpdateGeneralProjectPrivilegeRelationList,queryGeneralProjectPrivilegeRelationListPage} from '@/api/general/project/generalProjectPrivilegeRelationApi';
import {exportGeneralProjectInfoExcel,saveOrUpdateGeneralProjectInfo,saveOrUpdateGeneralProjectInfoList,saveGeneralProjectInfo,saveGeneralProjectInfoList,deleteGeneralProjectInfo,queryGeneralProjectInfo,queryGeneralProjectInfoListPage,updateGeneralProjectInfo,deleteGeneralProjectInfoList} from '@/api/general/project/generalProjectInfoApi';
import {mapGetters} from 'vuex';
import { reqCommonMsg } from '@/util/reqCommonMsg';
import {filterFormat} from '@/util/util';

export default {
  data() {
    return {
      //文件选择器的打开方式 add新增、edit修改、view 查看
      openType: 'edit',

      projectManagerUserId: '',
      roleId: '',
      //权限设置对话框
      setPrivilegeDialog: false,
      activeTabName: 'menuPrivilege',
      menuTreeData: [],
      menuTreeProps: {
        children: 'children',
        label: 'name'
      },
      treeValue: [],
      oldTreeValue: [],
      isTabChange: false,
      currentTabName: '',
      dialogTitle: '',
      fullscreenLoading: false,

      currentRow: {},
      importDataArea: '',
      batchAddDialog: false,
      form: {},
      openType: '',
      selectionList: [],
      loading: true, 
      showColumn: [],
      option: {
        labelPosition: 'right',
        labelSuffix: '：',
        labelWidth: 120,
        dialogTop: '50',
        indexFixed:true, 
        stripe:true,
        calcHeight: 80,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        selection: true,
        addBtn: true,
        viewBtn: false,
        delBtn: true,
        cancelBtn: true,
        printBtn:false,
        saveBtn: true,
        filterBtn:true,          
        menuWidth: 220,
        menuPosition: 'center',
        dialogDirection:'rtl',
        dialogType:'dialog',
        dialogFullscreen:false,
        dialogClickModal:false,
        dialogWidth: '70%',
        highlightCurrentRow:  true,
        searchShow:true,
        column: [
          {
            label: '项目编号',
            prop: 'projectNo', 
            type: 'input', 
            search: true,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '项目名称',
            prop: 'projectName', 
            type: 'input', 
            search: true,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '项目分类',
            prop: 'projectCategory', 
            type: 'select', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '项目简称',
            prop: 'projectShortName', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '需求编号',
            prop: 'demandNo', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '需求名称',
            prop: 'demandName', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '主办部门',
            prop: 'makeMainDeptName', 
            type: 'tree', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            props: {
              label: 'orgName',
              value: 'orgName'
            },
            dicData:[]
          },
          {
            label: '协办部门',
            prop: 'makeAssistDeptName', 
            type: 'tree', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            props: {
              label: 'orgName',
              value: 'orgNo'
            },
            dicData:[]
          },
          {
            label: '主办科室',
            prop: 'bizMainDeptName', 
            type: 'tree', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            props: {
              label: 'orgName',
              value: 'orgNo'
            },
            dicData:[]
          },
          {
            label: '项目经理',
            prop: 'projectManagerName', 
            type: 'select', 
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            dicData:[],
            remote: true,
            dicMethod:'get',
            dicUrl: '/platform/sysUserInfo/querySysUserInfoListPage?optFlag=noorg&columnValue={{key}}&columnName=realName&tenantId='+localStorage.getItem('tenantId'),
            props: {
              label: 'realName',
              value: 'realName'
            },
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
          },
          {
            label: '建设方式',
            prop: 'buildWay', 
            type: 'select', 
            search: true,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '实施方式',
            prop: 'makeWay', 
            type: 'select', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          
          {
            label: '项目级别',
            prop: 'projectGrade', 
            type: 'select', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '优先等级',
            prop: 'priorLevel', 
            type: 'select', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            value: '中',
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[
              {
                label:'高',
                name:'高'
              },
              {
                label:'中',
                name:'中'
              },
              {
                label:'低',
                name:'低'
              }
            ]
          },
          {
            label: '预计工作量',
            prop: 'expectWorkload', 
            type: 'number', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            append:'人天',
            minRows: 0,
            value: 0,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '预算类目',
            prop: 'budgetClass', 
            type: 'select', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '预算金额',
            prop: 'budgetAmt', 
            type: 'number', 
            precision:2,
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            append:'万元',
            minRows: 0,
            value: 0,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '项目状态',
            prop: 'projectStatus', 
            type: 'select', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '计划开始日期',
            prop: 'planBeginDate', 
            type: 'date', 
            format:'yyyy-MM-dd',
            valueFormat: 'yyyy-MM-dd',
            pickerOptions: {
              disabledDate(time) {
                return time.getTime() > Date.now();
              }
            },
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '计划完成日期',
            prop: 'planFinishDate', 
            type: 'date', 
            format:'yyyy-MM-dd',
            valueFormat: 'yyyy-MM-dd',
            pickerOptions: {
              disabledDate(time) {
                return time.getTime() > Date.now();
              }
            },
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '实际开始日期',
            prop: 'actualBeginDate', 
            type: 'date', 
            format:'yyyy-MM-dd',
            valueFormat: 'yyyy-MM-dd',
            pickerOptions: {
              disabledDate(time) {
                return time.getTime() > Date.now();
              }
            },
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '实际完成日期',
            prop: 'actualFinishDate', 
            type: 'date', 
            format:'yyyy-MM-dd',
            valueFormat: 'yyyy-MM-dd',
            pickerOptions: {
              disabledDate(time) {
                return time.getTime() > Date.now();
              }
            },
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '立项文档',
            prop: 'apprProjectFileAddress', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 24,
            sortable: false,
            hide: true,
            overHidden: true,
            formslot:true,
            value: [],
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '项目描述',
            prop: 'projectDesc', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 24,
            sortable: false,
            hide: true,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '备注',
            prop: 'remark', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 24,
            sortable: false,
            hide: true,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
        ]
      },
      data: [],
      // 请求参数区
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      reqParams: {
        singleBody: {},
        listBody: [{}],
        sqlCondition:[],
        orderRule: {},
        currentPage: 1,
        pageSize: 10
      },
      commonData: null,
      conditions: [],
      orderRules: [],
      singleBody: {}
    };
  },
  
  computed: {
    ...mapGetters(['website','userInfo','genOrgTree','permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.general_project_i_add, false),
        viewBtn: this.vaildData(this.permission.general_project_i_view, false),
        delBtn: this.vaildData(this.permission.general_project_i_delete, false),
        editBtn: this.vaildData(this.permission.general_project_i_edit, false),
        printBtn: this.vaildData(this.permission.general_project_i_print, false),
        searchBtn:this.vaildData(this.permission.general_project_i_search, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push({id : ele.id});
      });
      return ids;
    } 
  },
  methods: {
    /**
     * 历史记录方法
     */
    getHistoryRecord () {
      setTimeout(() => {
        this.$refs.historyRecord.getUpdateHistoryRecord(this.form.id);
      })
    },
    /**
     * 创建项目管理员
     */
    addProjectAdminUser(){
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择一个租户！');
        return false;
      }
      else if (this.selectionList.length > 1) {
        this.$message.warning('请选择一个租户！');
        return false;
      }
      else if(this.currentRow.projectManagerName == ''){
        this.$message.warning('项目经理不能为空！');
        return  false;
      }
      // 添加项目信息到缓存
      this.$store.dispatch('setProjectInfo', this.selectionList[0]);
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading'
      });
      this.reqParams.singleBody = {
        tenantId: this.selectionList[0].tenantId,
        userName: this.selectionList[0].projectManagerName
      }
      this.commonData = reqCommonMsg(this.reqParams)
      createProjectAdminUser(this.commonData).then(() => {
        this.singleBody={};
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '初始化管理员成功!'
        });
        loading.close();
      }, error => {
        loading.close();
      });
    },
    
    /**
     * 复选框选择
     */
    getCheckedNodes(arg1,arg2) {
      let superId = this.userInfo.tenantId+'00000000';
      if(arg2.checkedKeys.length> this.checkedLen){
        this.treeValue.push(arg1.id)
        let _node = this.$refs.menuTree.getNode(arg1.id)
        //递归选中父节点
        let setParentChecked = (arg0,arg1) => {
          let str = ','+arg0.join(',')+','; 
          let parantId = arg1.data.parentId;
          if(parantId != ''&&  parantId != superId && !str.includes(','+parantId+',')){
            arg0.push(parantId)
            setParentChecked(arg0,this.$refs.menuTree.getNode(parantId));
          }
        }
        setParentChecked(this.treeValue,_node);
        //递归选中子节点
        let setChildChecked = (arg0,arg1) => {
          let str = ','+arg0.join(',')+',';
          if(arg1.children.length>0){
            arg1.children.map(item=>{
              if(item.id&&!str.includes(','+item.id+',')){
                arg0.push(item.id);
              }
              setChildChecked(arg0,item);
            });
          }
        }
        setChildChecked(this.treeValue,arg1);
        this.$refs.menuTree.setCheckedKeys(this.treeValue);
      }else if(arg2.checkedKeys.length< this.checkedLen){
        this.treeValue.splice(this.treeValue.indexOf(arg1.id),1);
        //递归取消选中子节点
        let setChildUnChecked = (arg0,arg1) => {
          let str = ','+arg0.join(',')+',';
          if(arg1.children.length>0){
            arg1.children.map(item=>{
              if(str.includes(','+item.id+',')){
                arg0.splice(arg0.indexOf(item.id),1);
              }
              setChildUnChecked(arg0,item);
            });
          }
        }
        setChildUnChecked(this.treeValue,arg1);
        this.$refs.menuTree.setCheckedKeys(this.treeValue);
      }
      this.checkedLen=this.$refs.menuTree.getCheckedKeys().length;
    },
    /**
     * 打开权限设置对话框
     */
    async handleSetPrivilege(row){
      this.dialogTitle = '项目权限设置-['+row.projectName+']';
      this.setPrivilegeDialog = true;
      this.currentRow = row;
      this.fullscreenLoading = true;
      //获取已选菜单权限
      await this.getCheckedResource('1')
      //获取所有菜单
      await this.getMenuTree();
    },
    /**
     * 获取已选择的资源
     */
    async getCheckedResource(type){
      this.treeValue = [];
      this.singleBody = {
        resourceType : type,
        projectId: this.currentRow.id,
      }
      this.reqParams =  {
        singleBody: this.singleBody,
        currentPage: 1, 
        pageSize: this.website.maxPageSize
      }
      this.commonData = reqCommonMsg(this.reqParams)
      await queryGeneralProjectPrivilegeRelationListPage(this.commonData).then(res => {
        res.data.body.listBody.forEach(element => {
          this.treeValue.push(element.resourceId);
        });
        this.oldTreeValue=[];
        this.oldTreeValue = this.deepClone(this.treeValue)
      }, error => {
      });
    },
    /**
     * 获取树形菜单
     */
    async getMenuTree(){
      // 加载树形机构列表
      this.singleBody = {
        tenantId: this.userInfo.tenantId,
        parentMenuId: this.userInfo.tenantId+'00000000',
        menuCategory: '2',
        menuLevel: '1'
      }
      this.reqParams =  {
        singleBody: this.singleBody,
        currentPage: 1, 
        pageSize: this.website.maxPageSize
      }
      this.commonData = reqCommonMsg(this.reqParams)
      await querySysMenuTree(this.commonData).then(res => {
        this.singleBody = {};
        this.menuTreeData = res.data.body.listBody; 
        this.fullscreenLoading = false;
      }, error => {
        this.fullscreenLoading = false;
      });
    },
     
    /**
     * 添加权限记录
     */
    handleSavePrivilege() {
      let resultList = this.changedList();
      if(resultList.length > 0){
        this.reqParams =  {
          transCode: '0001',
          listBody: resultList
        }
        this.commonData = reqCommonMsg(this.reqParams)
        saveOrUpdateGeneralProjectPrivilegeRelationList(this.commonData).then(() => {
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '保存成功!'
          });
          this.addMenuDialog = false;
          this.fullscreenLoading = false;
          this.oldTreeValue = [];
          this.oldTreeValue = this.deepClone(this.treeValue)
        }, error => {
          window.console.log(error);
          this.fullscreenLoading = false;
        });
      }
      else{
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '未发生变化,无需保存!'
        });
        this.fullscreenLoading = false;
      }
    },
    /**
     * 获取变化列表
     */
    changedList(){
      // 判断当前活动tab
      let type = '1';
      this.treeValue = this.$refs.menuTree.getCheckedKeys(false);
      this.fullscreenLoading = true;
      // 前后选择对比，给新增和删除的打上标识
      let resultList = [];
      // 原列表不存在的表示新增的元素
      let inOldValue = false;
      let inNewValue = false;
      this.treeValue.forEach(element => {
        inOldValue = false;
        for(var i = 0 ; i < this.oldTreeValue.length; i++){
          if (element == this.oldTreeValue[i]) {
            inOldValue = true;
            i = this.oldTreeValue.size + 1;
          }
        }
        //若没找到表示新增元素
        if(!inOldValue){
          resultList.push({
            resourceType: type,
            projectId: this.currentRow.id,
            resourceId: element,
            validFlag: '1'
          })
        }
      });

      //新列表中不存在 表示 删除元素
      this.oldTreeValue.forEach(element => {
        inNewValue = false;
        for(var i = 0 ; i < this.treeValue.length; i++){
          if (element == this.treeValue[i]) {
            inNewValue = true;
            i = this.treeValue.size + 1;
          }
        }
        //若没找到表示删除元素
        if(!inNewValue){
          resultList.push({
            resourceType: type,
            projectId: this.currentRow.id,
            resourceId: element,
            validFlag: '0'
          })
        }
      });
      return resultList;
    },
    
    /**
     * 选择文件后由子组件触发修改fileList
     */
    changeFileList(fileList){
      this.currentRow.apprProjectFileAddress = fileList;
    },
    
    /**
     * 加载列表数据
     */
    onLoad(page) {
      this.loading = true;
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage: page.currentPage, 
        pageSize: page.pageSize
      }
      this.commonData = reqCommonMsg(this.reqParams)
      queryGeneralProjectInfoListPage(this.commonData).then(res => {
        const data = res.data.body;
        this.page.total = data.total;
        this.data = data.listBody;
        this.loading = false;
        this.selectionClear();
      }, error => {
        this.loading = false; 
      });
    },
    /**
     * 新增一条记录
     */
    rowSave(row, done, loading) {
      this.reqParams.singleBody = row;
      // 解析用户名（用户ID）
      let formatUser = this.$util.formatUserName(row.projectManagerName);
      this.reqParams.singleBody.projectManagerName = formatUser.userId; 
      this.reqParams.singleBody.projectManagerRealName = formatUser.userName;
      this.commonData = reqCommonMsg(this.reqParams)
      saveGeneralProjectInfo(this.commonData).then(() => {
        done();
        this.singleBody={};
        this.onLoad(this.page);
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        window.console.log(error);
        loading();
      });         
      //console.log("row = ",row ,loading)
    },
    /**
     * 修改一条记录
     */
    rowUpdate(row, index, done, loading) { 
      this.reqParams.singleBody = row;
      // 解析用户名（用户ID）
      let formatUser = this.$util.formatUserName(row.projectManagerName);
      this.reqParams.singleBody.projectManagerName = formatUser.userId; 
      this.reqParams.singleBody.projectManagerRealName = formatUser.userName;
      this.commonData = reqCommonMsg(this.reqParams)
      updateGeneralProjectInfo(this.commonData).then(() => {
        done();
        this.singleBody={}
        this.onLoad(this.page);
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        window.console.log(error);
        loading();
      });
      console.log('loading = ',loading)
    },
    /**
     * 删除一条记录
     */
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reqParams.singleBody = row;
          this.commonData = reqCommonMsg(this.reqParams);
          return deleteGeneralProjectInfo(this.commonData);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
        }).catch(() => {});
    },
    /**
     * 双击打开详细窗口
     */
    handleRowDBLClick (row, event) {
      if(this.permission.general_project_i_dbclick){
        this.$refs.crud.rowView(row,row.$index);
      }
    },
    /**
     * 批量新增记录
     */
    openBatchAddDialog(){
      this.batchAddDialog = true;
    },
    // 
    handleImport() {
      const loading = this.$loading({
        lock: true,
        text: '处理中...',
        spinner: 'el-icon-loading',
      });
      var dataList = new Array();
      if(this.importDataArea){
        var lineList = this.importDataArea.split('\n')
        lineList.forEach((element,index) => {
          if(element.trim() != ''){
            var field = element.split('\t')
            var fieldList = {
              projectNo:field[0].trim(),
              projectName:field[1].trim(),
              projectCategory:field[2].trim(),
              projectShortName:field[3].trim(),
              demandNo:field[4].trim(),
              demandName:field[5].trim(),
              makeMainDeptName:field[6].trim(),
              bizMainDeptName:field[7].trim(),
              makeAssistDeptName:field[8].trim(),
              buildWay:field[9].trim(),
              makeWay:field[10].trim(),
              projectManagerName:field[11].trim(),
              projectGrade:field[12].trim(),
              priorLevel:field[13].trim(),
              expectWorkload:field[14].trim(),
              budgetClass:field[15].trim(),
              budgetAmt:field[16].trim(),
              projectStatus:field[17].trim(),
              planBeginDate:field[18].trim(),
              planFinishDate:field[19].trim(),
              actualBeginDate:field[20].trim(),
              actualFinishDate:field[21].trim(),
              apprProjectFileAddress:field[22].trim(),
              projectDesc:field[23].trim(),
              remark:field[24].trim(),
            }
            dataList[index] = fieldList
            //console.log('fieldList = ',fieldList)
          }
        });
        //批量写入记录
        this.reqParams.listBody = dataList;
        this.commonData = reqCommonMsg(this.reqParams)
        saveGeneralProjectInfoList(this.commonData).then(() => {
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
          loading.close();
        }, error => {
          window.console.log(error);
          loading.close();
        });      
      }
      else{
        this.loading=false;
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '数据格式不正确!'
        });
      }
    },
    /**
     * 搜索重置
     */
    searchReset() {
      this.conditions =[];
      this.singleBody = {};
      this.onLoad(this.page);
    },
    /**
     * 搜索
     */
    searchChange(params, done) {
      this.singleBody = params
      this.page.currentPage = 1;
      this.onLoad(this.page);
      done();
    },
    refreshChange(){
      this.onLoad(this.page);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    /**
     * 处理批量删除
     */
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reqParams.listBody = this.ids;
          this.commonData = reqCommonMsg(this.reqParams);
          return deleteGeneralProjectInfoList(this.commonData);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        }).catch(() => {});
    },
    /**
     * 拷贝记录
     */
    handleCopy(row){
      this.$confirm('确定复制数据?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading=true;
        let copyValue=row;
        copyValue.id='0';
        copyValue.dataSign='0'
        copyValue.tableName='拷贝 '+ copyValue.tableName; 
        this.reqParams.singleBody = copyValue;
        this.commonData = reqCommonMsg(this.reqParams)
        saveSysToolTables(this.commonData).then(() => {
          this.singleBody={};
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
          this.loading=false;
        }, error => {
          window.console.log(error);
          this.loading=false;
        });
      }).catch(() => {});       
    },
    /**
     * 打开编辑、查询弹窗前查询记录
     */  
    beforeOpen(done, type) {
      this.reqParams =  {
        singleBody: {
          id:this.form.id
        }
      }
      this.openType = type;
      let commonData = reqCommonMsg(this.reqParams)
      if (['edit', 'view'].includes(type)) {
        queryGeneralProjectInfo(commonData).then(res => {
          this.form = res.data.body.singleBody;
          this.form.projectManagerName = res.data.body.singleBody.projectManagerRealName+'('+ res.data.body.singleBody.projectManagerName +')';
          this.form.apprProjectFileAddress = JSON.parse(this.form.apprProjectFileAddress);
        });
      }
      done();
    },
    /**
     * 翻页查询
     */
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    /**
     * 更改每页条数
     */
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    /**
     * 自定义查询条件
     */
    filterChange(result) {
      this.page.currentPage = 1;
      this.conditions = filterFormat(result)
      this.onLoad(this.page);
    },
    /**
     * 列表排序
     */
    sortChange(val){
      this.orderRules=val
      this.onLoad(this.page);
    },
  
    /**
     * 导出Excel
     */
    exportExcel() {
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage:1, 
        pageSize: 100
      }
      // console.log('reqParams = ',this.reqParams)
      this.commonData = reqCommonMsg(this.reqParams)
      exportGeneralProjectInfoExcel(this.commonData);
    },
    /**
     * 获取业务字典参数
     */
    async getBizDict() {
      let dicData = await this.$params.getBizDict('["projectCategory","buildWay","makeWay","projectGrade","budgetClass","projectStatus"]');
      this.findObject(this.option.column, 'projectCategory').dicData = dicData.projectCategory;
      this.findObject(this.option.column, 'buildWay').dicData = dicData.buildWay;
      this.findObject(this.option.column, 'makeWay').dicData = dicData.makeWay;
      this.findObject(this.option.column, 'projectGrade').dicData = dicData.projectGrade;
      this.findObject(this.option.column, 'budgetClass').dicData = dicData.budgetClass;
      this.findObject(this.option.column, 'projectStatus').dicData = dicData.projectStatus;
    },
  },
  created() {
       
  },
  mounted() {
    this.showColumn = this.$getStore({name:  this.userInfo.userId +'generalProjectInfoColumn'});
    //获取业务字典
    setTimeout(() => {
      this.getBizDict();
    }, 100);
    //加载机构
    let getOrgTreeTimer = setInterval(() => {
      if(this.genOrgTree){
        const makeMainDeptName = this.findObject(this.option.column, 'makeMainDeptName');
        const bizMainDeptName = this.findObject(this.option.column, 'bizMainDeptName');
        const makeAssistDeptName = this.findObject(this.option.column, 'makeAssistDeptName');
        let orgTree = [];
        this.genOrgTree.forEach(element => {
          if(element.orgType == '1'){
            orgTree.push(element);
          }
        });
        //console.log('====orgtree === ', orgTree);
        makeMainDeptName.dicData = [];
        makeMainDeptName.dicData = this.deepClone(orgTree); 
        bizMainDeptName.dicData = [];
        bizMainDeptName.dicData = this.deepClone(orgTree); 
        makeAssistDeptName.dicData = [];
        makeAssistDeptName.dicData = this.deepClone(orgTree); 
        clearInterval(getOrgTreeTimer);
      }
    }, 100);
  },
  watch: {
    showColumn() {
      this.$setStore({name: this.userInfo.userId +'generalProjectInfoColumn', content: this.showColumn});
    }
  }
};
</script>
